package cn.shengchao.examstar.knowledge.infrastructure.repository.impl;

import cn.hutool.core.util.StrUtil;
import cn.shengchao.examstar.knowledge.domain.entity.KnowledgePoint;
import cn.shengchao.examstar.knowledge.domain.repository.KnowledgePointRepository;
import cn.shengchao.examstar.knowledge.infrastructure.converter.KnowledgePointConverter;
import cn.shengchao.examstar.knowledge.infrastructure.dao.TKnowledgePointTreeMapper;
import cn.shengchao.examstar.knowledge.infrastructure.dao.po.TKnowledgePointTree;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Repository;

import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Set;
import java.util.Map;
import java.util.HashMap;

/**
 * 知识点仓储实现类
 */
@Repository
@RequiredArgsConstructor
public class KnowledgePointRepositoryImpl implements KnowledgePointRepository {

    private final TKnowledgePointTreeMapper knowledgePointTreeMapper;
    private final KnowledgePointConverter knowledgePointConverter;

    @Override
    public KnowledgePoint save(KnowledgePoint knowledgePoint) {
        TKnowledgePointTree po = knowledgePointConverter.toPO(knowledgePoint);
        if (po.getId() == null) {
            knowledgePointTreeMapper.insert(po);
        } else {
            knowledgePointTreeMapper.updateById(po);
        }
        return knowledgePointConverter.toEntity(po);
    }

    @Override
    public Optional<KnowledgePoint> findById(Long id) {
        TKnowledgePointTree po = knowledgePointTreeMapper.selectById(id);
        return Optional.ofNullable(po).map(knowledgePointConverter::toEntity);
    }

    @Override
    public List<KnowledgePoint> findBySpecificationTypeId(Long specificationTypeId) {
        LambdaQueryWrapper<TKnowledgePointTree> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(TKnowledgePointTree::getSpecificationTypeId, specificationTypeId)
                .eq(TKnowledgePointTree::getStatus, 1)
                .orderByAsc(TKnowledgePointTree::getSort);
        List<TKnowledgePointTree> poList = knowledgePointTreeMapper.selectList(wrapper);
        return poList.stream().map(knowledgePointConverter::toEntity).collect(Collectors.toList());
    }

    @Override
    public List<KnowledgePoint> findByParentId(Long parentId) {
        LambdaQueryWrapper<TKnowledgePointTree> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(TKnowledgePointTree::getParentId, parentId)
                .eq(TKnowledgePointTree::getStatus, 1)
                .orderByAsc(TKnowledgePointTree::getSort);
        List<TKnowledgePointTree> poList = knowledgePointTreeMapper.selectList(wrapper);
        return poList.stream().map(knowledgePointConverter::toEntity).collect(Collectors.toList());
    }

    @Override
    public void delete(Long id) {
        TKnowledgePointTree po = new TKnowledgePointTree();
        po.setId(id);
        po.setStatus(0L);  // 标记删除
        knowledgePointTreeMapper.updateById(po);
    }

    @Override
    public List<KnowledgePoint> getKnowledgePointsByIds(List<Long> ids) {
        // 1. 查询所有叶子节点
        List<TKnowledgePointTree> leafNodes = knowledgePointTreeMapper.selectBatchIds(ids);

        // 2. 收集所有path中的根节点
        Set<Long> allPathIds = new HashSet<>(ids);
        for (TKnowledgePointTree leaf : leafNodes) {
            String[] pathIds = leaf.getPath().split("/");
            if(StrUtil.isNotEmpty(pathIds[0])) {
                allPathIds.add(Long.valueOf(pathIds[0]));
            }
        }

        // 3. 查询所有相关节点
        List<TKnowledgePointTree> allNodes = knowledgePointTreeMapper.selectBatchIds(new ArrayList<>(allPathIds));

        // 4. 转换为实体
        Map<Long, KnowledgePoint> id2Entity = new HashMap<>();
        for (TKnowledgePointTree node : allNodes) {
            KnowledgePoint kp = knowledgePointConverter.toEntity(node);
            id2Entity.put(kp.getId(), kp);
        }

        // 5. 按parentId分组
        for (KnowledgePoint kp : id2Entity.values()) {
            if (StrUtil.isNotEmpty(kp.getPath())) {
                Long parentId = Long.valueOf(kp.getPath().split("/")[0]);
                if (kp.getParentId() != null && id2Entity.containsKey(parentId)) {
                    KnowledgePoint parent = id2Entity.get(parentId);
                    if (parent.getChildren() == null) {
                        parent.setChildren(new ArrayList<>());
                    }
                    parent.getChildren().add(kp);
                }
            }
        }

        // 6. 找到所有根节点（parentId为null或不在id2Entity中的）
        List<KnowledgePoint> roots = new ArrayList<>();
        for (KnowledgePoint kp : id2Entity.values()) {
            if (StrUtil.isNotEmpty(kp.getPath())) {
                Long parentId = Long.valueOf(kp.getPath().split("/")[0]);
                if (!id2Entity.containsKey(parentId)) {
                    roots.add(kp);
                }
            }else {
                roots.add(kp);
            }
        }
        return roots;
    }
}